package com.ecnu.jiagou.damai.service;

import com.ecnu.jiagou.damai.entity.User;
import com.ecnu.jiagou.damai.exception.GlobalException;
import com.ecnu.jiagou.damai.mapper.UserMapper;
import com.ecnu.jiagou.damai.result.CodeMsg;
import com.ecnu.jiagou.damai.result.Result;
import com.ecnu.jiagou.damai.utils.MD5Util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public Result<User> getUserById(Long userid, String password){
        //System.out.println(userid);
        User user = userMapper.getUserById(userid);
        //user.getUserid();
        //System.out.println(user == null);
        if(user == null){
            throw new GlobalException(CodeMsg.NOT_EXIST);
        }
        String dbpass = user.getPassword();
        String salt = "1a2b3c4d";
        String calcPass = MD5Util.formPassToDBPass(password, salt);
        if (!calcPass.equals(dbpass)) {
            throw new GlobalException(CodeMsg.PASSWORD_ERROR);
            //return Result.error()
        }

        return Result.success(user);
    }

    @Transactional
    public Result<Map<String,String>> addUser(User user){
        long insertUser = userMapper.addUser(user);
        long insertAccount = userMapper.addAccount(user);
        if(insertUser != insertAccount){
            return Result.error(CodeMsg.ERROR);
        }
        User res = userMapper.getUserByUsername(user.getUsername());
        Map<String,String> map = new HashMap<>();
        String id = String.format("%08d",res.getUserid());
        map.put("userid",id);
        map.put("username",res.getUsername());
        
        return Result.success(map);
    }

    public User getUserByName(String username){
        return userMapper.getUserByUsername(username);
    }

    public User getAccountById(Long userid){
        return userMapper.getUserById(userid);
    }

    @Transactional
    public boolean updateInfo(User user){
        boolean flag = false;
        User pre = userMapper.getUserByUsername(user.getUsername());
        if(pre != null && pre.getUserid() != user.getUserid()){
            return false;
        }else{
            flag = userMapper.updateUser(user);
        }
        if(flag){
            return userMapper.updateAccount(user);
        }
        return false;
    }
}
